package framework.server.cfg;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

public abstract class AbstractCfgHandler extends DefaultHandler {

	File file;

	public File getFile() {
		return file;
	}

	@Override
	public int hashCode() {
		if (file != null) {
			try {
				return file.getCanonicalFile().hashCode();
			} catch (IOException e) {
			}
		}
		return 0;
	}

	/** Accumulate parsed text */
	protected StringBuffer accumulator = new StringBuffer();

	public static String configurationPath(String filename) {
		return filename;
	}

	public void parseURI(File file) {
		try {
			this.file = file;
			/** Create a JAXP "parser factory" for creating SAX parsers */
			SAXParserFactory factory = SAXParserFactory.newInstance();
			
			/** Configure the parser factory for the type of parsers we require */
			//factory.setValidating(false); // No validation required

			/** Now use the parser factory to create a SAXParser object
			 Note that SAXParser is a JAXP class, not a SAX class */
			SAXParser parser = factory.newSAXParser();

			/** Create a SAX input source for the file argument */
			InputSource input = new InputSource(new FileReader(file));

			/** Give the InputSource an absolute URL for the file, so that
			 it can resolve relative URLs in a <!DOCTYPE> declaration, e.g. */
			input.setSystemId(file.getAbsolutePath());

			/** Finally, tell the parser to parse the input and notify the handler */
			parser.parse(input, this);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/** 
	 * When the parser encounters plain text (not XML elements), it calls
	 * this method, which accumulates them in a string buffer
	 */
	@Override
	public void characters(char[] buffer, int start, int length) {
		accumulator.append(buffer, start, length);
	}

	/** This method is called when warnings occur */
	@Override
	public void warning(SAXParseException exception) {
		System.err.println("WARNING: line " + exception.getLineNumber() + ": " + exception.getMessage());
	}

	/** This method is called when errors occur */
	@Override
	public void error(SAXParseException exception) {
		System.err.println("ERROR: line " + exception.getLineNumber() + ": " + exception.getMessage());
	}

	/** This method is called when non-recoverable errors occur. */
	@Override
	public void fatalError(SAXParseException exception) throws SAXException {
		System.err.println("FATAL: line " + exception.getLineNumber() + ": "  + exception.getMessage());
		throw (exception);
	}
}
